package com.zlm.weather.service.impl;

import cn.hutool.core.util.PinyinUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.zlm.weather.constant.RedisEnum;
import com.zlm.weather.pojo.City;
import com.zlm.weather.pojo.CityList;
import com.zlm.weather.pojo.Province;
import com.zlm.weather.pojo.ProvinceList;
import com.zlm.weather.service.CityService;
import com.zlm.weather.util.AnnotationUtil;
import com.zlm.weather.util.ConfigProperties;
import com.zlm.weather.util.XmlBuilderUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: 郑
 * @Date: Create in 2020-1-17.
 */
@Slf4j
@Service
public class CityServiceImpl implements CityService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ConfigProperties configProperties;

    @Override
    public List<Province> listProvince() throws Exception{
        String provinceUrl = configProperties.getProvince_url();
        String result = HttpUtil.get(provinceUrl);
        ProvinceList list = (ProvinceList) XmlBuilderUtil.xmlStrToObject(ProvinceList.class, result);
        redisTemplate.opsForValue().set(RedisEnum.PROVINCEPER.getKey(), JSON.toJSONString(list.getListProvince()));
        return list.getListProvince();
    }

    @Override
    public List<City> listCity(String cityName) throws Exception {
        String cityUrl = configProperties.getCity_url();
        String pinYin = PinyinUtil.getPinYin(cityName);
        AnnotationUtil.updateParam("com.zlm.weather.pojo.CityList",pinYin);
        String result = HttpUtil.get(cityUrl+pinYin+".xml");
        CityList list = (CityList) XmlBuilderUtil.xmlStrToObject(CityList.class, result);
        redisTemplate.opsForValue().set(RedisEnum.CITYPER.getKey()+cityName, JSON.toJSONString(list.getCityList()));
        return list.getCityList();
    }
}
